﻿namespace Rzrlf.SP.Innovator.WebParts.CompositeWebPart
{
    [System.ComponentModel.ToolboxItemAttribute(false)]
    public class CompositeWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/Rzrlf.SP.Innovator.WebParts/CompositeWebPart/CompositeWebPartUserControl.ascx";
        
        private Rzrlf.SP.Innovator.WebParts.CompositeWebPart.CompositeWebPartUserControl _control = null;
        private System.Web.UI.UpdatePanel _updatePanel = null;

        public CompositeWebPart()
        {
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            _control = base.Page.LoadControl(_ascxPath) as Rzrlf.SP.Innovator.WebParts.CompositeWebPart.CompositeWebPartUserControl;

            if (_data != null)
            {
                _control.Data = _data;
            }

            _updatePanel = new System.Web.UI.UpdatePanel();
            _updatePanel.ContentTemplateContainer.Controls.Add(_control);

            base.Controls.Add(_updatePanel);
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            if (_data != null && _data.TriggerControls != null)
            {
                foreach (System.Web.UI.Control ctrl in _data.TriggerControls.Keys)
                {
                    System.Web.UI.AsyncPostBackTrigger trigger = new System.Web.UI.AsyncPostBackTrigger();
                    trigger.ControlID = ctrl.ID;
                    trigger.EventName = _data.TriggerControls[ctrl];

                    _updatePanel.Triggers.Add(trigger);
                }
            }

            base.RenderContents(writer);
        }

        #region Web Part Communication Implementation...

        private Rzrlf.SP.Innovator.WebParts.IStructureData _data = null;

        [System.Web.UI.WebControls.WebParts.ConnectionConsumer("Composite Data")]
        public void SynchData(Rzrlf.SP.Innovator.WebParts.IStructureData data)
        {
            _data = data;

            if (_control != null)
            {
                _control.Data = _data;
            }
        }

        #endregion
    }
}
